var prices = [7,1,5,3,6,4,5,6,2,8,1,9];

// var maxProfit = function(prices) {
//     /*
// 		循环prices，其元素两两相减，将正整数的结果相加并最终输出
// 	*/
// 	return prices.reduce((res, item, index, arr) => {
// 		return res += (arr[index + 1] - item) > 0 ? (arr[index + 1] - item) : 0;
// 	}, 0)
// };

var maxProfit = function(prices) {
	let result = [];
	let i = j = 0;
	while(true){
		if(prices[j] === undefined){break;}
		
		if(prices[j] >= prices[j + 1] || prices[j + 1] === undefined){
			let first = prices[j] - prices[i];
			j++;
			if(first > 0){
				result.push(first);
				i = j;
			}else{
				i++;
			}
		}else{
			j++;
		}
	}
	// result.length 就是交易的次数
	console.log(result);
	return result.reduce((res, item) => {
		return res + item;
	}, 0);
};

console.log(maxProfit(prices));